# Maintainer: David Macek <david.macek.0@gmail.com>
# Contributor (Arch Linux): Gustavo Alvarez <sl1pkn07@gmail.com>
# Contributor: Felix Huettner <huettner94@gmx.de>

_realname=lpeg
pkgbase=mingw-w64-lua-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-lua-${_realname}"
         "${MINGW_PACKAGE_PREFIX}-lua51-${_realname}")
pkgver=1.1.0
pkgrel=1
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://www.inf.puc-rio.br/~roberto/lpeg/'
license=('spdx:MIT')
makedepends=("${MINGW_PACKAGE_PREFIX}-lua"
             "${MINGW_PACKAGE_PREFIX}-lua51"
             "${MINGW_PACKAGE_PREFIX}-cc")
source=("https://www.inf.puc-rio.br/~roberto/${_realname}/${_realname}-${pkgver}.tar.gz"
        "lpeg-0.12-makefile.patch"
        "LICENSE")
sha256sums=('4b155d67d2246c1ffa7ad7bc466c1ea899bbc40fef0257cc9c03cecbaed4352a'
            'a278438fa745de8e0390f438b5f73229e57d44192457048e0f99d76526d578b4'
            '6be7688c9c648e7c7cde693081be938c869a10aa4de09fe0a4c4c1d66b3cf03d')

prepare() {
  cd "${_realname}-${pkgver}"
  patch -p1 -i "${srcdir}/lpeg-0.12-makefile.patch"
  sed -i 's/lpeg.so/lpeg.dll/' makefile

  mkdir -p "${srcdir}/build-${MSYSTEM}" "${srcdir}/build-51-${MSYSTEM}"
  cp -rf * "${srcdir}/build-${MSYSTEM}"
  sed -i 's/env lua5.1/env lua/' "${srcdir}/build-${MSYSTEM}/test.lua"
  cp -rf * "${srcdir}/build-51-${MSYSTEM}"
}

build() {
  cd "${srcdir}/build-${MSYSTEM}"
  make CC=${CC} LUADIR=${MINGW_PREFIX}/include LDFLAGS="$(pkg-config lua --libs)"

  cd "${srcdir}/build-51-${MSYSTEM}"
  make CC=${CC} LUADIR=${MINGW_PREFIX}/include/lua5.1 LDFLAGS="$(pkg-config lua5.1 --libs)"
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  make test

  cd "${srcdir}/build-51-${MSYSTEM}"
  make test
}

package_lua-lpeg() {
  pkgdesc='Pattern-matching library for Lua (mingw-w64)'
  depends=("${MINGW_PACKAGE_PREFIX}-lua")

  cd "${srcdir}/build-${MSYSTEM}"

  local luaver=$(pkg-config lua --modversion | sed -r 's/^([0-9]+[.][0-9]+)[.][0-9]+$/\1/')
  install -Dm755 lpeg.dll "${pkgdir}${MINGW_PREFIX}/lib/lua/${luaver}/lpeg.dll"
  install -Dm644 re.lua "${pkgdir}${MINGW_PREFIX}/share/lua/${luaver}/re.lua"
  install -Dm644 "${srcdir}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/lua-lpeg/LICENSE"
}

package_lua51-lpeg() {
  pkgdesc='Pattern-matching library for Lua 5.1 (mingw-w64)'
  depends=("${MINGW_PACKAGE_PREFIX}-lua51")

  cd "${srcdir}/build-51-${MSYSTEM}"
  install -Dm755 lpeg.dll "${pkgdir}${MINGW_PREFIX}/lib/lua/5.1/lpeg.dll"
  install -Dm644 re.lua "${pkgdir}${MINGW_PREFIX}/share/lua/5.1/re.lua"
  install -Dm644 "${srcdir}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/lua51-lpeg/LICENSE"
}

# template start; name=mingw-w64-splitpkg-wrappers; version=1.0;
# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
# template end;
